<script setup lang="ts">
import { ElLoading, ElMessage, ElMessageBox, genFileId, vLoading } from "element-plus";
import type {
    Action,
    FormInstance,
    UploadInstance,
    UploadProps,
    UploadRawFile,
} from "element-plus";
import { $bus } from "@/event_bus/event_bus_index";
import { reactive, ref } from "vue";
import { throttle } from "@/utils/NslUtil4Fn";
import ElSvgIcon from "@/components/el-svg-icon/el_svg_icon_index.vue";
import * as bbuBoardStatusApi from '@/api/current_status/bbu_board_status/bbu_board_status_api_index'
import { NslUtils } from "@/utils/NslUtil";
import { EnumUploadSatusValue } from "@/types/global/enums/enums_types";

//todo: 导入有两种方式，1种是追加导入，1种是覆盖导入

const dialog = reactive({
    visible: false,
    title: "设备板卡信息导入",
    width: 800,
});

const loadingRef = ref(false);

const fullscreenLoadingRef = ref();


const openFullScreenLoading = () => {
    fullscreenLoadingRef.value= ElLoading.service({
    lock: true,
    text: '处理中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
//   setTimeout(() => {
//     loading.close()
//   }, 2000)
}

const closeFullScreenLoading=()=>{
    fullscreenLoadingRef.value.close();
}

const importFormRef = ref<FormInstance>();

const uploadRef = ref<UploadInstance>();

const uploadStatusDialogVisibleRef = ref(false);

interface TypeUploadInfo {
    importRecordTotalCount?: number;

    toImportFileName?: string;
}
const uploadStatusInfoInit = {
    importRecordTotalCount: undefined,

    toImportFileName: undefined,
};

const uploadStatusInfoRef = ref<TypeUploadInfo>(
    Object.assign({}, uploadStatusInfoInit)
);

const openDialog = () => {
    dialog.visible = true;
};

const openDialogCallback = () => {
    uploadRef.value!.clearFiles();
};

const closeDialogCallBack = () => {
    importData.value = Object.assign({}, importDataInit);
    importFormRef.value!.resetFields();
};

type ImportDataType = {
    deptId: number | undefined;
    fileList: File[] | undefined;
    file: undefined | File;
};

const importDataInit = {
    deptId: undefined,
    fileList: [],
    file: undefined,
};

const importData = ref<ImportDataType>({
    deptId: undefined,
    fileList: [],
    file: undefined,
});
/** Excel文件 Change */
function handleFileChange(file: any) {
    console.log("in handleFileChange");
    console.log("file.name =", file.name);
    if (!file?.name.endsWith(".xlsx")) {
        ElMessageBox.alert("上传文件类型必须为*.xlsx", "上传文件类型错误", {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: "确定",
            callback: (action: Action) => {
                uploadRef.value!.clearFiles();
                return;
            },
        });
    }
    importData.value.file = file.raw;
}

/** Excel文件 Exceed 超出文件数量时  */
const handleFileExceed: UploadProps["onExceed"] = (files) => {
    // uploadRef.value!.clearFiles();
    console.log("in handleFileExceed");
    const file = files[0] as UploadRawFile;
    console.log("importData.value.file?.name =", importData.value.file?.name);

    if (!file?.name.endsWith(".xlsx")) {
        ElMessageBox.alert("上传文件类型必须为*.xlsx", "上传文件类型错误", {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: "确定",
            callback: (action: Action) => {
                uploadRef.value!.clearFiles();
                return;
            },
        });
    }
    file.uid = genFileId();
    uploadRef.value!.handleStart(file);
    importData.value.file = file;
};
const handleSubmit = throttle(
    () => {
        if (!importData.value?.file) {
            ElMessage.warning("上传Excel文件不能为空");
            return false;
        }
        // loadingRef.value=true;
        openFullScreenLoading()
        bbuBoardStatusApi
            .importExcel(importData.value?.file)
            .then(({ data }) => {
                const uploadStatusEnumValue = data.uploadStatusEnum.value;
                if (
                    uploadStatusEnumValue ===
                    EnumUploadSatusValue.UPLOAD_SUCCESS_EVERY_THINK_OK
                ) {
                    ElMessageBox.alert(
                        "本次导入记录数：" + data.msgList[0],
                        "导入成功",
                        {
                            // if you want to disable its autofocus
                            // autofocus: false,
                            confirmButtonText: "确定",
                            callback: (action: Action) => {
                                uploadRef.value!.clearFiles();
                                dialog.visible = false;
                                $bus.emit(
                                    "current-status-apparatus-room-table-query"
                                );
                                return;
                            },
                        }
                    );
                } else {
                    ElMessageBox.alert(
                        "失败原因：" + data.msgList[0],
                        "导入失败",
                        {
                            // if you want to disable its autofocus
                            // autofocus: false,
                            confirmButtonText: "确定",
                            callback: (action: Action) => {
                                uploadRef.value!.clearFiles();
                                return;
                            },
                        }
                    );
                }
            })
            .finally(()=>{
                // loadingRef.value=false;
                closeFullScreenLoading();
                $bus.emit('bbu-return-board-table-query');
            });
    },
    3000,
    true
);

function closeUploadStatusDialogCallback() {
    console.log("in close call back");
    uploadStatusInfoRef.value = Object.assign({}, uploadStatusInfoInit);
}

defineExpose({
    openDialog,
});

function NslUtil4Fn(arg0: () => false | undefined, arg1: number) {
    throw new Error("Function not implemented.");
}
</script>
<template>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        :width="dialog.width"
        :close-on-click-modal="false"
        v-loading="loadingRef"
        @close="closeDialogCallBack"
        @open="openDialogCallback"
    >
        <fieldset>
            <legend>&nbsp;注意事项&nbsp;</legend>
            <ul>
                <li>
                    1. 地市、厂家、板卡类型必须为枚举字段。
                    <br />
                    地市：省内18地市名称
                    <br />
                    厂家：中兴、华为、大唐
                    <br />
                    板卡类型：主控板、电源板、基带板和机框+风扇
                    <br />
                </li>
                <li>2. 数值类的项目，必须填入数值，空的话，默认为0。</li>
            </ul>
        </fieldset>
        <!-- 用户导入表单 -->
        <el-form :model="importData" label-width="100px" ref="importFormRef"  >
            <el-form-item label="Excel文件">
                <el-upload
                    ref="uploadRef"
                    action=""
                    drag
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    :limit="1"
                    :auto-upload="false"
                    :file-list="importData.fileList"
                    :on-change="handleFileChange"
                    :on-exceed="handleFileExceed"
                >
                    <!-- <el-icon class="el-icon--upload">
                        <icon-ep-plus />
                    </el-icon> -->
                    <ElSvgIcon a-icon-name="el-icon-upload" :aSize="50" />
                    <div class="el-upload__text">
                        将文件拖到此处，或
                        <em>点击上传</em>
                    </div>
                    <template #tip>
                        <div>上传文件类型必须为：*.xlsx</div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <!-- 弹窗底部操作按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleSubmit"
                    >确 定</el-button
                >
                <el-button @click="() => (dialog.visible = false)"
                    >取 消</el-button
                >
            </div>
        </template>
    </el-dialog>
</template>
<style lang="scss" scoped>
legend {
    font-size: 16px;
    font-weight: 500;
    color: black;
}
fieldset {
    border: 1px solid #a8abb2;
    margin-bottom: 15px;
}
fieldset {
    ul li {
        padding: 10px;
        padding-top: 15px;
        margin-bottom: 10px;
    }
}
</style>
